import 'dart:typed_data';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:similar_img/entity.dart';
import 'package:similar_img/image_provider.dart';
import 'package:similar_img/similar_img.dart';
import 'package:similar_img/thumbnail.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _similarImgPlugin = SimilarImg();
  final List<List<Uint8List>> _dataList = [];
  final List<List<AssetEntity>> _assetEntityList = [];
  final List<List<Map>> _mapList = [];

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _similarImgPlugin.getPlatformVersion() ??
          'Unknown platform version';
      List<List<AssetEntity>> list =
          await _similarImgPlugin.fectchSimilarArray();
      for (var element in list) {
        List<Map> mapList = [];
        List<AssetEntity> assetEntityList = [];
        for (var child in element) {
          var map = {};
          var id = child.id;
          var width = child.width;
          var height = child.height;
          var option = ThumbnailOption.ios(size: ThumbnailSize(width, height));
          map["id"] = id;
          map["option"] = option.toMap();
          mapList.add(map);
          assetEntityList.add(child);
        }
        _mapList.add(mapList);
        _assetEntityList.add(assetEntityList);
      }
      for (var list in _mapList) {
        List<Uint8List> dataList = [];
        for (var item in list) {
          var data = await _similarImgPlugin.getThumb(item);
          dataList.add(data);
        }
        _dataList.add(dataList);
      }

      // 查看第一个图的原图地址
      final path =
          await _similarImgPlugin.getOrigin(_assetEntityList.first.first.id);
      if (kDebugMode) {
        print("path=$path");
      }
      // 删除最后一个
      final remove = await _similarImgPlugin.removeAeest(
          _assetEntityList.last.last.id, _assetEntityList.last.last.typeInt);
      if (kDebugMode) {
        print("remove=$remove");
      }
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Text('Running on: $_platformVersion\n'),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final item = _assetEntityList[index];
                  final data = _dataList[index];
                  return Container(
                    height: 200,
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    child: GridView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      itemCount: item.length ?? 0,
                      scrollDirection: Axis.horizontal,
                      gridDelegate:
                          const SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200,
                      ),
                      itemBuilder: (context, index) {
                        final entityChild = item[index];
                        final dataChild = data[index];
                        return Container(
                          color: Colors.grey[200],
                          child: Image(
                            image: AssetEntityImageProvider(
                                entityChild, dataChild),
                          ),
                        );
                      },
                    ),
                  );
                },
                childCount: _assetEntityList.length ?? 0,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
